package cc.messcat.web.system;

import cc.messcat.entity.area.Area;
import cc.messcat.entity.system.ApplicationProperties;
import cc.messcat.entity.system.TableMaintenance;
import cc.messcat.service.area.AreaService;
import cc.messcat.service.fupin.PoorFamilyService;
import cc.messcat.service.fupin.PoorVillageService;
import cc.messcat.service.helpunits.HelpunitsService;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.FilenameFilter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 定时任务类
 */
@Component
public class Task {

	private static Logger logger = LoggerFactory.getLogger(Task.class);

	@Autowired
	private CacheManager manager;

	@Autowired
	private PoorFamilyService pfs;

	@Autowired
	private PoorVillageService pvs;

	@Autowired
	private HelpunitsService helpunitsService;

    @Autowired
    private TableMaintenance tableMaintenance;

    @Autowired
    private AreaService areaService;

	/**
	 * 定时首页统计
	 */
	@SuppressWarnings("rawtypes")
	public void updateIndexStatistics() {
		Cache cache = manager.getCache("indexStatistics");
		
		List totalPoor = pfs.totalPoor();
		cache.remove("totalFamily");
		cache.put(new Element("totalFamily", totalPoor));
		
		List unitsNr = helpunitsService.unitsNr();
		cache.remove("unitsNumber");
		cache.put(new Element("unitsNumber",unitsNr));
		
		List unitsNr2 = pvs.unitsNr();
		cache.remove("NemberPoorVillages");
		cache.put(new Element("NemberPoorVillages", unitsNr2));
		
		List queryMainPovertyCauses = pfs.queryMainPovertyCauses();
		cache.remove("poorCauseStat");
		cache.put(new Element("poorCauseStat", queryMainPovertyCauses));
		
		List complexQueryIncomeInfo = pfs.complexQueryIncomeInfo();
		cache.remove("income");
		cache.put(new Element("income", complexQueryIncomeInfo));

        logger.info("首页统计完成");
	}
	
	/**
	 * 定时清理临时文件
	 */
	public void cleanTempFile() {
		ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext();
		File file = new File(servletContext.getRealPath("") + "/WEB-INF/temp");
		try {
			if (file.exists()) {
				for (File f : file.listFiles(new FilenameFilter() {
					@Override
					public boolean accept(File dir, String name) {
						return FilenameUtils.isExtension(name, "tmp");
					}
				})) {
					f.delete();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.info("清理临时文件成功");
	}

	/**
	 *  定时更新贫困村中的贫困户数和贫困人口数字段
	 */
	public void updatePoorFamilyCountAndFamilyCountOfPoorVillage() {

        List<Area> allVillage = areaService.getALLVillage();
        Set<Long> ids = new HashSet<>();
        for(Area e : allVillage) {
            ids.add(e.getId());
        }

        for(Long id : ids) {
            tableMaintenance.updatePoorFamilyCount(ApplicationProperties.getAnnual(),id);
            tableMaintenance.updateFamilyCount(ApplicationProperties.getAnnual(),id);
        }

        logger.info("贫困村表贫困户数，贫困人口数字段维护完成");
    }
}
